12. Mockito Verify

Mockito Verify

ND079 JPND C3 L5 A08a Mockito Verify V3

Verify Methods Called

Mockito.when allows us to override the behavior of methods, but we need a different tool to tell if a method was called. That tool is verify.

If we had a method that saved results to a database, we might want to write a test to check if that method saved the correct values. Testing the full interaction between a service and a database is no longer in the scope of a unit test, however, so what we will do instead is check if the method to save the results was called.

public class PersistentSalesService implements SalesService {

   private SalesRepository salesRepository;

   public PersistentSalesService(SalesRepository salesRepository) {
       this.salesRepository = salesRepository;
   }

   @Override
   public String fizzBuzz(int i) {
       String retVal = fizzBuzzInternal(i);
       salesRepository.saveResults(i, retVal); //verify THIS method
       return retVal;
   }
}

PersistentSalesServiceTest

@ExtendWith(MockitoExtension.class)
class PersistentSalesServiceTest {

    @Mock
    private SalesRepository salesRepository;
    private PersistentSalesService persistentSalesService;

    @BeforeEach
    void init() {
        persistentSalesService = new PersistentSalesService(salesRepository);
    }

    @RepeatedTest(15)
    void persistentSalesService_fizzBuzz_savesToDatabase(RepetitionInfo repetitionInfo) {
        int i = repetitionInfo.getCurrentRepetition();
        String result = persistentSalesService.fizzBuzz(i);
        verify(salesRepository).saveResults(i, result);
    }
}

ND079 JPND C3 L5 A08b Mockito Verify With Additional Parameters

Verify with ArgumentMatchers

//checks that any string is saved for the current integer
verify(salesRepository).saveResults(i, anyString());

Verify the Number of Interactions

//fail if saveResults not called exactly 2 times
verify(salesRepository, times(2)).saveResults(i, anyString());

//fail if saveResults called more than 10 times
verify(salesRepository, atMost(10)).saveResults(i, anyString());

//fail if saveResults not called 3 or more times
verify(salesRepository, atLeast(3)).saveResults(i, anyString());

Verify Order of Interactions

//fail if delete and saveResults are not called in order
InOrder inOrder = Mockito.inOrder(salesRepository);
inOrder.verify(salesRepository).delete(i);
inOrder.verify(salesRepository).saveResults(i, result);